﻿// Form that posts to the server using AJAX
define([
    'Wjs/ui/widgets/forms/Form'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'AjaxForm',

        internal: {

            base: Wjs.getType('Form')
        },

        // Sets the HttpRequest to POST to the server using AJAx
        setHttpRequest: function (httpRequest) {
            var me = this;

            httpRequest
                .onSuccess(function (response, callback) {
                    me.acceptChanges(); // Set the fields as not modified

                    if (me.fieldChangedHandler) {

                        me.fieldChangedHandler(); // Fire the field changed event
                    }

                    if (me.submitHandler) {

                        me.submitHandler(response);
                    }
                })
                .onComplete(function () {

                    me.hideMask();
                });

            me.httpRequest = httpRequest;

            return me;
        },

        getHttpRequest: function () {

            return this.httpRequest;
        },

        submit: function (bypassBeforeSubmit) {
            var request = this.httpRequest;

            if (this.getBase().submit.call(this, bypassBeforeSubmit) === false) {

                return; // Do not submit
            }

            request.setParameters(this.serialize());

            this.showMask();

            request.send();
        }

    });

});